Skip to content

Add trigger and audit logging example to PostgreSQL advanced concepts#22

Merged
fahimahammed merged 2 commits intofahimahammed:mainfrom
DivyanshGarg380:add-trigger-audit-example
Oct 3, 2025
Merged

Add trigger and audit logging example to PostgreSQL advanced concepts#22
fahimahammed merged 2 commits intofahimahammed:mainfrom
DivyanshGarg380:add-trigger-audit-example

Conversation

@DivyanshGarg380
Copy link
Copy Markdown
Contributor

Description:
This PR enhances the Advanced Concepts in PostgreSQL documentation by adding a comprehensive example demonstrating how to create and use triggers for auditing database changes.

Changes included:

  • Target Table Creation
    • Added an example target_table to demonstrate the trigger functionality.
  • Audit Table Creation.
    • Added an audit_table that logs all INSERT, UPDATE, and DELETE operations performed on the target table.
    • Includes columns for event_type, event_time, table_name, old_data, and new_data.
  • Trigger Function (log_changes)
    • Created a PL/pgSQL trigger function to automatically log changes to the audit_table.
    • Handles all three operations:
      • INSERT: Logs the new record.
      • UPDATE: Logs both old and new record states.
      • DELETE: Logs the deleted record.
    • Uses to_jsonb() to store the row data in JSONB format for flexible querying.
  • Trigger Attachment
    • Demonstrates how to attach the log_changes trigger function to the target_table.
    • Trigger executes AFTER INSERT, UPDATE, or DELETE for each affected row.

Benefits:

  • Provides a real-world use case of triggers in PostgreSQL.
  • Helps readers understand how to maintain an audit trail automatically.
  • Complements existing documentation on constraints, joins, and other advanced PostgreSQL features.

Usage:
Once merged, users can follow this example to implement audit logging for any table in their database.

@fahimahammed fahimahammed merged commit a7411dd into fahimahammed:main Oct 3, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants